<?php
// $Id: db.mysql.php 1 2009-10-03 03:22:16Z zaurum $

class DBmysql {
	protected
			$db,
			$errors = array(),
			$tpref = '',
			$dbh;
	
    const MAX_SQL_LENGTH = 2097152;

    public function MAX_SQL_LENGTH(){
        return self::MAX_SQL_LENGTH;
    }

    public function add_error_message($e) {
        if (isset($e)) {
            $this->errors[] = $e;
        }
    }

    public function get_error_messages($clear = true) {
        $rc = $this->error;
        if ($clear) $this->errors = array();
        return $rc;
    }
    
    public function clear_error_messages() {
        $this->errors = array();
    }

    public function __construct($db) {
		if (isset($db['prefix'])) $this->tpref = $db['prefix'];
		$this->connect($db);
    }

    public function __destruct() {
		$this->disconnect();
    }

    public function connect(&$dbdata) {
// Populate data
        $this->db = $dbdata;
// Now do actual connecting: attach port value if present
        $dbhost = $this->db['host']; if ($this->db['port'] != '') $dbhost .= ':' . $this->db['host'];
        $this->dbh = mysql_connect($dbhost, $this->db['user'], $this->db['password']);
// If couldn't connect, place error message and exit
        if (!$this->dbh) {
            $this->add_error_message(mysql_error());
            return false;
        }
// Select DB if successfully
        if (!mysql_select_db($this->db['database'], $this->dbh)) {
            $this->add_error_message(mysql_error());
            return false;
        }
// Select default charset UTF8
		mysql_query('SET CHARACTER SET utf8', $this->dbh);
		mysql_query("SET NAMES utf8", $this->dbh);
        return true;
    }
    
    public function disconnect() {
        if (isset($this->dbh)) {
            if (!mysql_close($this->dbh)) {
                $this->add_error_message(mysql_error());
                return false;
            }
        }
        return true;
    }

    private function query($sql) {
        if (!is_string($sql)) return false;
        $this->res = mysql_query($sql, $this->dbh);
        if ($this->res === false) {
            $this->add_error_message(mysql_error());
            $this->res = null;
            return false;
        }
        return true;
    }

    private function fetch_all($ashash = true) {
        $rc = array();
        if (is_resource($this->res)) {
            $mode = $ashash ? MYSQL_ASSOC : MYSQL_NUM;
            while ($row = mysql_fetch_array($this->res, $mode)) {
                $rc[] = $row;
            }
        }
        return $rc;
    }

    public function execute($sql, $ashash = true) {
        $rc = $this->query($sql);
        
        if ($rc) {
            if (is_resource($this->res)) {
                return $this->fetch_all($ashash); 
            }
        }
        return $rc;
    }

//
// DBmysql::fexecute($sql_template, $params=false, $ashash=true)
// Prepares SQL out of template and fetches the results
// Parameters
//   $sql_template - string like 
//                      "SELECT * FROM {tpref}table WHERE val1=%d" 
//   $params params for the template, e.g. like array(
//      array('s', 'string param'),
//      array('d', intval1),
//      array('d', intval2),
//   )
//   $ashash - return as hashes or nuemric indices array
    public function fexecute($sql_template, $params=false, $ashash = true){
        $prepared_params = array($sql_template);
        if (is_array($params)){
            if (count($params)>0){
// Prepare params for putting them into $sql_template
                foreach ($params as $p){
                    $v = $p;
                    if (is_array($p)){
                        $v = $p[1];
                        switch ($p[0]){
                            case 's': 
                                $v = $this->quote(strval($v));
                                break;
                            case 'd':
                                $v = intval($v);
                                break;
                        }
                    }
                    $prepared_params[] = $v;
                }                
            }
// Generate SQL statement            
        }
        elseif ($params !== false){
            $prepared_params[] = $params;
        }
            
        $sql = str_replace("{tpref}", $this->tpref, call_user_func_array('sprintf', $prepared_params));
        return $this->execute($sql);
    }

    public function quote($src) {
        return mysql_real_escape_string(strval($src));
    }
    
    public function affected_rows() {
        if (isset($this->dbh)) {
            return mysql_affected_rows($this->dbh);
        } else return 0;
    }
}
?>
